﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Linq;
using System.Data;

using ECCIT;
using ECCIT.Business.Model;
using Lucene.Net.Documents;

using OgilvyOne.Model;
using OgilvyOne.Utility;
using OgilvyOne.BLL;
using OgilvyOne.DALFactory;
using OgilvyOne.UKNow.DALFactory;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.IDAL;
using OgilvyOne.UKNow.ServiceReference;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.DAL;

namespace OgilvyOne.UKNow.BLL
{
    public class EventsBLL : IGenerateHtml, ICnEnMapping
    {
        public int LanguageID { get; set; }
        
        public EventsBLL(int langID)
        {
            this.LanguageID = langID;
        }

        public int IsSpecial { get; set; }

        //新增活动
        public ResultInfo Save(EventsModel info)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.Save(info);
        }
        //获取所有活动
        public IList<EventsModel> selectevents()
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetAllEventsModels();
        }
        //mff
        //根据所选语言,获取不重名的活动
        public List<EventsModel> seleventsByName(int langid)
        {
            this.LanguageID = langid;
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventModelsByName(langid);
        }
        //mff
        //根据所选语言和活动名称,获取活动的ID
        public IList<EventsModel> selEveByNandL(int langid,string eventName)
        {
            this.LanguageID = langid;
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEveByNandL(langid, eventName);
        }
        //mff
        //获取特色活动
        public IList<EventsModel> selectevents(int isSpecial)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetAllEventsModels(isSpecial);
        }
        /*修改人：穆凤凤
        * 修改时间：2012-03-05
        * 修改内容：
        *      新增加方法 获得按姓名查找出来的活动实体 selEventByName
        *      有mff注释的为本次修改的代码
        */
        //mff
        //按活动名称搜索活动记录
        public IList<EventsModel> selEventByName(string ename, int? state,int? isspecial)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventsModelByName(ename, state,isspecial);
        }
        //mff
        //根据活动eid 获取该活动信息
        public EventsModel selEvent(int eid)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventsModelByID(eid);
        }

        //修个单个活动的发布状态
        public void modPubOne(int eid)
        {
            List<int?> list = new List<int?>();
            list.Add(eid);

            IDALEvents use = EventsDALFactory.Create(LanguageID);
            IDALEventsImage imageuse = EventsImageDALFactory.Create(LanguageID);
            IDALEventsVideo videouse = EventsVideoDALFactory.Create(LanguageID);
            EventsModel model = use.GetEventsModelByID(eid); //查看该活动的当前发布状态
            if (model.State > 0) //该活动的当前为发布状态
            {
                use.UnPublish(list);
                //设置为该活动的state为0 不发布 (传递参数 eid 和 int=0)
                imageuse.editPubState(eid);
                videouse.editPubState(eid);
            }
            else
            {
                use.Publish(list);
                //设置该活动的state为1 发布     (传递参数 eid 和 int=1)
            }
        }
        ////设置单个活动是否为特色活动
        public void modSetSpecial(int eid)
        {
            List<int?> list = new List<int?>();
            list.Add(eid);

            IDALEvents use = EventsDALFactory.Create(LanguageID);

            EventsModel model = use.GetEventsModelByID(eid); //查看该特色是否为特色活动
            if (model.IsSpecial > 0) //该活动是否为特色活动
            {
                use.SetNotSpecial(list);
                //设置为该活动的isSpecial为0 非特色活动 (传递参数 eid 和 int=0)
            }
            else
            {
                use.SetIsSpecial(list);
                //设置该活动的isSpecial为1 特色活动     (传递参数 eid 和 int=1)
            }
        }
        //删除单个活动的数据(目前页面过来的id是 string)
        public ResultInfo delEvent(int eid)
        {
            IList<int?> list = new List<int?>();
            list.Add(eid);
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.Delete(list);
        }

        public PagingList GetFilteredEventsModels(int cityID, int artFormID, string yearMonth, int date, int currentPageIndex)
        {
            int pageSize = 12;
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currentPageIndex, pageSize, null);
            PagingList models = EventsDALFactory.Create(LanguageID).GetFilteredEventsModels(cityID, artFormID, yearMonth, date, pagingParams);
            return models;
        }

        public ITemplateType GetTemplateType(IStaticGeneratableModel model)
        {
            EventsTemplateType etl= new EventsTemplateType((EventsModel)model);
            etl.LanguageID = this.LanguageID;
            return etl;
        }

        /// <summary>
        ///     生成活动详情页HTML
        /// </summary>
        /// <param name="model"></param>
        public ResultInfo GenerateHtml(IStaticGeneratableModel baseModel, string dir)
        {
            if (!string.IsNullOrEmpty(((EventsModel)baseModel).Education))
            {
                EventsRoundModel ERModel = new EventsRoundModel();
                ERModel.RoundContent = ((EventsModel)baseModel).Education;
                ERModel.TemplateID = ((EventsModel)baseModel).LanguageID == 2052 ? 206 : 207;
                ERModel.ColumnID = ((EventsModel)baseModel).ColumnID;
                ERModel.HtmlFileName = ((EventsModel)baseModel).HtmlFileName;
                ERModel.ID = ((EventsModel)baseModel).ID;
                GenerateEventRoundHtml(ERModel, dir);
            }
            ResultInfo result = new ResultInfo(false);
            ITemplateType templateType = GetTemplateType(baseModel);
            string html = templateType.GetHtml();
            if (string.IsNullOrEmpty(html)) return result;

            try
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath("~" + dir + "/") + GetHtmlFileName((EventsModel)baseModel);
                FileUtil.SaveHtmlFile(filename, html);
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        public ITemplateType GetTemplateTypeRound(EventsRoundModel roundModel)
        {
            EventsRoundTemplateType etl = new EventsRoundTemplateType((EventsRoundModel)roundModel);
            etl.LanguageID = this.LanguageID;
            return etl;
        }

        private ResultInfo GenerateEventRoundHtml(EventsRoundModel roundModel,string dir)
        {
            ResultInfo result = new ResultInfo(false);
            ITemplateType templateType = GetTemplateTypeRound(roundModel);
            string html = templateType.GetHtml();
            if (string.IsNullOrEmpty(html)) return result;

            try
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath("~" + dir + "/") + GetEventsRoundFileName((EventsRoundModel)roundModel);
                FileUtil.SaveHtmlFile(filename, html);
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        public IStaticGeneratableModel GetModelByID(int id)
        {
            return selEvent(id);
        }

        public IList<IStaticGeneratableModel> GetAllStaticPublishModels(int? columnID)
        {
            return EventsDALFactory.Create(LanguageID).GetPublishedEventsModels(this.IsSpecial).Cast<IStaticGeneratableModel>().ToList<IStaticGeneratableModel>();
        }

        public string GetHtmlFileName(IStaticGeneratableModel model)
        {
            if (model == null) return null;
            string fileName = model.HtmlFileName;
            if (string.IsNullOrEmpty(fileName))
                fileName = model.ID + ".html";
            return fileName;
        }

        public string GetEventsRoundFileName(IStaticGeneratableModel model)
        {
            if (model == null) return null;
            //string fileName = (model.HtmlFileName).Split(',')[0] + "_round";
            string fileName = GetHtmlFileName(model).Split('.')[0] + "_round";
            if (string.IsNullOrEmpty(fileName))
                fileName = model.ID + "_round";
            return fileName + ".html";
        }

        /// <summary>
        /// 2012-6-6 李学明，加上了特色活动 include 的问题(
        /// </summary>
        /// <returns></returns>
        public IList<Document> CreateLuceneDocuments()
        {
            #region 临时处理方法          
            IList<EventsModel> models1 = EventsDALFactory.Create(LanguageID).GetPublishedEventsModels(0);
            IList<EventsModel> models2 = EventsDALFactory.Create(LanguageID).GetPublishedEventsModels(1);
            List<EventsModel> models =
                (models1.Cast<EventsModel>().ToList().Union(models2.Cast<EventsModel>().ToList())).ToList();
                    
            #endregion
            IList<Document> documents = new List<Document>();
            foreach (EventsModel model in models)
            {
                Document doc = new Document();
                doc.Add(!string.IsNullOrEmpty(model.UpLoadHtmlName)
                            ? new Field("html", model.Detail + GetIncludeHtml(model.UpLoadHtmlName), Field.Store.YES,
                                        Field.Index.ANALYZED)
                            : new Field("html", model.Detail, Field.Store.YES, Field.Index.ANALYZED));

                doc.Add(new Field("title", model.Title, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("url", string.Format("/{0}/events/{1}", (this.LanguageID==2052) ? "cn" : "en", GetHtmlFileName(model)), Field.Store.YES, Field.Index.NOT_ANALYZED));
                documents.Add(doc);
            }

            return documents;
        }

        /// <summary>
        /// 取特色活动的include 的html 内容 2012-6-6 李学明
        /// </summary>
        /// <param name="filename">include的html的文件的名字</param>
        /// <returns>返回的string </returns>
        private  string GetIncludeHtml(string filename)
        {
            try
            {
                var filePath = System.Web.HttpContext.Current.Server.MapPath("~/uploadfiles/htmlfile/" + filename);
                if (!File.Exists(filePath))
                {
                    return string.Empty;
                }

                using (var sr = new System.IO.StreamReader(filePath, Encoding.Default))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception)
            {
                
                throw;
            }
           
        }

        /// <summary>
        ///     获取活动ID为eventsID的活动的相关活动数据
        /// </summary>
        /// <param name="eventsID"></param>
        /// <returns></returns>
        public IList<EventsModel> GetRelatedEvents(int? eventsID, PagingParameter pagingParams)
        {
            return EventsDALFactory.Create(this.LanguageID).GetRelatedEvents(eventsID, pagingParams);
        }

        public PagingList GetCalendarDefaultEvents(int currengPageIndex, int pageSize)
        {
            int? requestCityID = GetRequestCityID();
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currengPageIndex, pageSize, null);
            return EventsDALFactory.Create(this.LanguageID).GetCalendarDefaultEvents(requestCityID, pagingParams);
        }

        /// <summary>
        ///     获取活动中的系列名称
        /// </summary>
        /// <returns></returns>
        public IList<EventsModel> GetSeriesMainEvents()
        {
            return EventsDALFactory.Create(this.LanguageID).GetSeriesMainEvents();
        }

        /// <summary>
        ///     根据一个活动ID，获取和这个活动同系列的活动
        /// </summary>
        /// <param name="eventsID">活动ID</param>
        /// <param name="includeSelf">是否包含当前活动本身</param>
        /// <returns></returns>
        public IList<EventsModel> GetSeriesEvents(int? eventsID, bool includeSelf)
        {
            return EventsDALFactory.Create(this.LanguageID).GetSeriesEvents(eventsID, includeSelf);
        }

        public IList<string> GetAllPublishedEventsYearMonth(int cityID, int artFormID)
        {
            return EventsDALFactory.Create(this.LanguageID).GetAllPublishedEventsYearMonth(cityID, artFormID);
        }

        public IList<ArtFormModel> GetAllPublishedEventsArtForms(int cityID)
        {
            return EventsDALFactory.Create(this.LanguageID).GetAllPublishedEventsArtForms(cityID);
        }

        public IList<int> GetAllPublishedEventsDate(int cityID, int artFormID, string yearMonth)
        {
            return EventsDALFactory.Create(this.LanguageID).GetAllPublishedEventsDate(cityID, artFormID, yearMonth);
        }

        public IList<int> GetEventsStartDateInPeriod(string startDate, string endDate)
        {
            IList<int> ds = EventsDALFactory.Create(this.LanguageID).GetEventsDayInPeriod(startDate, endDate);
            return ds;
        }

        /// <summary>
        ///     将源活动的图片以及视频数据同步到目标活动
        /// </summary>
        /// <param name="source">源活动，该model需要设置LanguageID以及ID两个属性</param>
        /// <param name="destination">目标活动，该model需要设置LanguageID以及ID两个属性</param>
        public void SyncEventsAttachments(EventsModel source, EventsModel destination)
        {
            EventsImageBLL destBll = new EventsImageBLL(destination.LanguageID.Value);
            destBll.DeleteImagesByEventsID(destination.ID.Value);   // 将目标活动中现有的图片数据删除

            EventsImageBLL srcBll = new EventsImageBLL(source.LanguageID.Value);
            IList<EventsImageModel> ileim = srcBll.GetAllEventsImageModels(source.ID);  // 获取源活动中的所有图片数据
            int count = ileim.Count;
            while (count > 0)
            {
                EventsImageModel eim = ileim[count - 1];
                eim.ID = null;
                eim.LanguageID = destination.LanguageID;
                eim.EventsID = destination.ID;
                destBll.Save(eim);

                count--;
            }

            EventsVideoBLL destVideoBll = new EventsVideoBLL(destination.LanguageID.Value);
            destVideoBll.DeleteVideosByEventsID(destination.ID.Value);  // 将目标活动中现有的视频数据删除

            EventsVideoBLL srcVideoBll = new EventsVideoBLL(source.LanguageID.Value);
            IList<EventsVideoModel> ilevm = srcVideoBll.GetAllEventsVideoModels(source.ID);

            count = ilevm.Count;
            while (count > 0)
            {
                EventsVideoModel evm = ilevm[count - 1];
                evm.ID = null;
                evm.LanguageID = destination.LanguageID;
                evm.EventsID = destination.ID;
                destVideoBll.Save(evm);

                count--;
            }
        }

        /// <summary>
        ///     根据年月获取在该月有活动的城市
        /// </summary>
        /// <param name="yearMonth"></param>
        /// <returns></returns>
        public IList<DictionaryManageModel> GetEventsCitiesByYearMonth(string yearMonth)
        {
            return EventsDALFactory.Create(this.LanguageID).GetEventsCitiesByYearMonth(yearMonth);
        }

        public PagingList GetUploadFilesByEventsID(int? eventsID, PagingParameter pagingParams)
        {
            if (!eventsID.HasValue) return null;

            // 获取所有图片数据
            EventsImageBLL imageBll = new EventsImageBLL(this.LanguageID);
            IList<UploadFileModel> images = imageBll.GetPublishedEventsImageModels(eventsID).Cast<UploadFileModel>().ToList();

            EventsVideoBLL videoBll = new EventsVideoBLL(this.LanguageID);
            IList<UploadFileModel> videos = videoBll.GetPublishedEventsVideoModels(eventsID).Cast<UploadFileModel>().ToList();
            IList<UploadFileModel> unions = videos.Union<UploadFileModel>(images).Cast<UploadFileModel>().ToList();

            PagingList list = new PagingList(new List<UploadFileModel>(), 0);
            if (unions.Count == 0) return list;

            if (pagingParams == null)
            {
                list.Capacity = unions.Count;
                for (int i = 0; i < unions.Count; ++i)
                    list.List.Add(unions[i]);
            }
            else
            {
                int totalRecordCount = unions.Count;
                int iPageSize = pagingParams.PageSize;
                int iCurrentPageIndex = pagingParams.CurrentPageIndex;

                if (iPageSize == 0) return null;
                
                list.Capacity = unions.Count;
                int iStartRecordIndex = iPageSize * iCurrentPageIndex;
                int iEndRecordIndex = iPageSize * (iCurrentPageIndex + 1);
                if (iEndRecordIndex > totalRecordCount) iEndRecordIndex = totalRecordCount;

                for (int i = iStartRecordIndex; i < iEndRecordIndex; ++i)
                    list.List.Add(unions[i]);
            }

            return list;
        }

        private int? GetRequestCityID()
        {
            string cityName = null;
            int? cityID=null;
            try
            {
                string ip = HttpRequestUtil.GetClientIP();
                IpAddressSearchWebServiceSoap service = new IpAddressSearchWebServiceSoapClient();
                string[] result = service.getCountryCityByIp(ip);
                if (result.Length == 2)
                {
                    JoinedString js = new JoinedString(result[1], " ");
                    if (js.Count > 0)
                        cityName = js[0];
                }

                if (cityName != null)
                    cityID = FindCityIDInDictionary(cityName);
            }
            catch (Exception ex)
            {
                cityName = null;
                cityID = null;
            }

            return cityID;
        }

        private int? FindCityIDInDictionary(string cityName)
        {
            int? cityID = null;
            DictionaryManageBLL bll = new DictionaryManageBLL();
            IList cities = bll.GetDictionary(393);
            foreach (DictionaryManageModel city in cities)
            {
                if (city.Cnname == cityName || cityName.StartsWith(city.Cnname) || city.Cnname.StartsWith(cityName))
                {
                    cityID = city.Cid;
                    break;
                }
            }

            return cityID;
        }

        /// <summary>
        /// 获取发布的今日焦点数据
        /// </summary>
        /// <param name="rows">行数</param>
        /// <returns>
        /// 返回前rows行的数据 默认按修改时间排序
        /// </returns>
        public IList GetHotspot(int rows)
        {
            if (this.LanguageID == 2052)
                return CmsArticleFrontFactory.create().GetHomeTopArticleList(518, rows);
            else
                return CmsArticleFrontFactory.create().GetHomeTopArticleList(519, rows);
        }

        /// <summary>
        /// 取今日热点列表 分页 2012-4-24 李学明 新加
        /// </summary>
        /// <param name="pageno"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public PageTools GetHotspotList(int pageno, int pagesize)
        {
            return GetArticleList(this.LanguageID == 2052 ? 518 : 519, pageno, pagesize);
        }

        public PageTools GetArticleList(int cloumnid,int pageno, int pagesize)
        {
            return CmsArticleFrontFactory.create().GetHotspotPageList(518, pageno, pagesize);
        }

        public string FormatEventsDate(string startTimeStr, string endTimeStr, string intervals)
        {
            if (this.LanguageID == (int)LanguageType.cn)
                return FormatEventsDate_Cn(startTimeStr, endTimeStr, intervals);
            else
                return FormatEventsDate_En(startTimeStr, endTimeStr, intervals);
        }

        public string FormatEventsDate(EventsModel model)
        {
            DateTime? startTime = model.StartTime;
            DateTime? endTime = model.EndTime;
            string formattedSTimeStr = null;
            if (startTime.HasValue)
            {
                if (this.LanguageID == (int)LanguageType.cn)
                    formattedSTimeStr = FormatDate_Cn(startTime);
                else
                    formattedSTimeStr = FormatDate_En(startTime);
            }

            string formattedETimeStr = null;
            if (endTime.HasValue)
            {
                if (this.LanguageID == (int)LanguageType.cn)
                    formattedETimeStr = FormatDate_Cn(endTime);
                else
                    formattedETimeStr = FormatDate_En(endTime);
            }

            return FormatEventsDate(formattedSTimeStr, formattedETimeStr, model.Week);
        }

        /// <summary>
        ///     格式化活动日期，用于显示
        /// </summary>
        /// <param name="startTime">活动开始日期，可以为null或""</param>
        /// <param name="endTime">活动结束日期，可以为null或""</param>
        /// <param name="intervals">形如：1,2,3,4,5,6,7的字符串，表示活动在每周n举办</param>
        /// <returns></returns>
        public string FormatEventsDate_Cn(string startTimeStr, string endTimeStr, string intervals)
        {
            DateTime? startTime = null;
            if (!string.IsNullOrEmpty(startTimeStr))
                startTime = DateTime.Parse(startTimeStr);

            DateTime? endTime = null;
            if (!string.IsNullOrEmpty(endTimeStr))
                endTime = DateTime.Parse(endTimeStr);

            return FormatEventsDate_Cn(startTime, endTime, intervals);
        }

        private string FormatEventsDate_Cn(DateTime? startTime, DateTime? endTime, string intervals)
        {
            string formattedSTimeStr = (startTime.HasValue) ? FormatDate_Cn(startTime) : null;
            string formattedETimeStr = (endTime.HasValue) ? FormatDate_Cn(endTime) : null;

            if (string.IsNullOrEmpty(formattedSTimeStr) && string.IsNullOrEmpty(formattedETimeStr))
                return "敬请期待";
            else if (string.IsNullOrEmpty(formattedSTimeStr))
                return formattedETimeStr;
            else if (string.IsNullOrEmpty(formattedETimeStr))
                return formattedSTimeStr;
            else
            {
                string joinChar = " 至 ";
                if (startTime.Value.Year == endTime.Value.Year)
                    return formattedSTimeStr + joinChar + formattedETimeStr.Substring(5);
                return formattedSTimeStr + joinChar + formattedETimeStr;
            }
        }

        public string FormatEventsDate_Cn(EventsModel model)
        {
            return FormatEventsDate_Cn(model.StartTime, model.EndTime, model.Week);
        }

        public string FormatDate_Cn(DateTime? dateTime)
        {
            if (!dateTime.HasValue) return "";

            string sFirst = "";
            string longFormatString = "yyyy年MM月dd日 HH:mm";
            string shortFormatString = "yyyy年MM月dd日";
            CultureInfo cultureInfo = null;

            string sStartTime = dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            if (sStartTime.EndsWith(" 00:00:00"))
                sFirst = dateTime.Value.ToString(shortFormatString, cultureInfo);
            else
                sFirst = dateTime.Value.ToString(longFormatString, cultureInfo);

            return sFirst;
        }

        private string FormatEventsDate_En(DateTime? startTime, DateTime? endTime, string intervals)
        {
            string formattedSTimeStr = (startTime.HasValue) ? FormatDate_En(startTime) : null;
            string formattedETimeStr = (endTime.HasValue) ? FormatDate_En(endTime) : null;

            if (string.IsNullOrEmpty(formattedSTimeStr) && string.IsNullOrEmpty(formattedETimeStr))
                return "TBC";
            else if (string.IsNullOrEmpty(formattedSTimeStr))
                return formattedETimeStr;
            else if (string.IsNullOrEmpty(formattedETimeStr))
                return formattedSTimeStr;
            else
            {
                string joinChar = "  to  ";
                if (startTime.Value.Year == endTime.Value.Year)
                {
                    // 英文日期处理
                    if (startTime.Value.Month != endTime.Value.Month)
                    {
                        int index = formattedSTimeStr.IndexOf(" ", 3);  // 获取d-MMMM-yyyy中MMMM后的"-"字符的索引

                        return formattedSTimeStr.Substring(0, index) + joinChar + formattedETimeStr;
                    }
                    else
                        return startTime.Value.Day + joinChar + formattedETimeStr;
                }
                return formattedSTimeStr + joinChar + formattedETimeStr;
            }
        }

        public string FormatEventsDate_En(string startTimeStr, string endTimeStr, string intervals)
        {
            DateTime? startTime = null;
            if (!string.IsNullOrEmpty(startTimeStr))
                startTime = DateTime.Parse(startTimeStr);

            DateTime? endTime = null;
            if (!string.IsNullOrEmpty(endTimeStr))
                endTime = DateTime.Parse(endTimeStr);

            return FormatEventsDate_En(startTime, endTime, intervals);
        }

        public string FormatEventsDate_En(EventsModel model)
        {
            return FormatEventsDate_En(model.StartTime, model.EndTime, model.Week);
        }

        public string FormatDate_En(DateTime? dateTime)
        {
            if (!dateTime.HasValue) return "";

            string sFirst = "";
            //string longFormatString = "d-MMMM-yyyy HH:mm";
            string shortFormatString = "d-MMMM-yyyy";
            CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");

            sFirst = dateTime.Value.ToString(shortFormatString, cultureInfo);
            int hour = dateTime.Value.Hour;
            int minute = dateTime.Value.Minute;
            if (dateTime.Value.Hour > 0 || dateTime.Value.Minute > 0)
            {
                string tt = (hour > 12) ? "p.m." : "a.m.";
                hour = (hour > 12) ? hour - 12 : hour;
                sFirst += " " + hour + "." + minute + " " + tt;
            }

            sFirst = sFirst.Replace("-", " ");
            return sFirst;
        }

        public IList<KeyValuePair<int, string>> RetrieveDropDownListItems()
        {
            IList<EventsModel> events = selectevents();
            IList<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
            foreach (EventsModel model in events)
                list.Add(new KeyValuePair<int, string>(model.ID.Value, model.Title));

            return list;
        }

        public DataTable GetList()
        {
            return EventsDALFactory.Create(this.LanguageID).GetAllList();
        }
        public IList<FavoriteEventsModel> GetMyEvents(int memberid, string begintime, string endtime, bool flag)
        {
            return EventsDALFactory.Create(this.LanguageID).GetMyEvents(memberid, begintime, endtime, flag);

        }

        /// <summary>
        /// 获取用户收藏并提醒的最近的一个活动
        /// </summary>
        /// <param name="memberid"></param>
        /// <returns></returns>
        public FavoriteEventsModelExt GetMyRecentlyEvent(int memberid)
        {
            IList<FavoriteEventsModelExt> list = EventsDALFactory.Create(this.LanguageID).GetMyRecentlyEvent(memberid);
            if(list!=null&&list.Count>0)
            {
                return list.OrderBy(p => p.COL_EVENTS_DATE).First();
            }
            return null;
          
        }


        public PagingList GetMyEvents(int userID, int pageSize, int currentPageIndex)
        {
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currentPageIndex, pageSize, null);
            return EventsDALFactory.Create(2052).GetMyEvents(userID, pagingParams);
        }

        /// <summary>
        /// 用的是这个方法
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="city"></param>
        /// <returns></returns>
        public PagingList GetMyEvents(int userID, int pageSize, int currentPageIndex,int city)
        {
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currentPageIndex, pageSize, null);
            return EventsDALFactory.Create(2052).GetMyEvents(userID, pagingParams,city);
        }

        public ResultInfo SaveSEOInfo(IStaticGeneratableModel model)
        {
            return ((StaticGeneratableDAL)EventsDALFactory.Create(this.LanguageID)).SaveSEOInfo((StaticGeneratableModel)model);
        }

        public ResultInfo GetSEOInfo(int id)
        {
            return ((StaticGeneratableDAL)EventsDALFactory.Create(this.LanguageID)).GetSEOInfo(id);
        }

        /// <summary>
        /// 获取特色活动分页
        /// </summary>
        /// <param name="pagingParams">分页参数类</param>
        /// <returns>返回PagingList</returns>
        public PagingList GetFeaturedPaging(PagingParameter pagingParams)
        {
            return EventsDALFactory.Create(this.LanguageID).GetFeaturedModel(pagingParams);
        }

        /// <summary>
        /// 验证当前用户收有没有收藏的活动
        /// </summary>
        /// <param name="memberid"></param>
        /// <returns></returns>
         public bool CheckMyEvents(int memberid)
         {
             return EventsDALFactory.Create(this.LanguageID).CheckMyEvents(memberid);
         }

         /// <summary>
         /// 用户是否赞过
         /// </summary>
         /// <param name="memberid"></param>
         /// <param name="eventid"></param>
         /// <returns></returns>
         public bool CheckUserUp(int memberid,int eventid)
         {
             return EventsDALFactory.Create(this.LanguageID).CheckUserUp(memberid, eventid);
         }

         public IList<EventsModel> GetEventsModelsByEventsIDs(IList<int?> ids)
         {
             return EventsDALFactory.Create(this.LanguageID).GetEventsModelsByEventsIDs(ids);
         }

         #region 后台专用
         public  IList<EventsModel> AfterGetAllEventsModels()
        {
            return EventsDALFactory.Create(this.LanguageID).AfterGetAllEventsModels();
        }

        public IList<EventsModel> AfterGetAllEventsModels(int isSpecial)
        {
            return EventsDALFactory.Create(this.LanguageID).AfterGetAllEventsModels(isSpecial);
        }

        public IList<EventsModel> AfterGetEventsModelByName(string ename, int? state, int? isspecial)
        {
            return EventsDALFactory.Create(this.LanguageID).AfterGetEventsModelByName(ename, state, isspecial);
        }
#endregion


        /// <summary>
        /// 验证活动是否在举行
        /// </summary>
        /// <param name="eventid">活动ID</param>
        /// <returns>true 是举行 false未举行</returns>
        public  bool CheckEventBegin(int eventid)
        {
            return EventsDALFactory.Create(this.LanguageID).CheckEventBegin(eventid);
        }

        /// <summary>
        /// 根据用户ID和活动ID验证是否收藏过活动
        /// </summary>
        /// <param name="memberid"></param>
        /// <param name="eventid"></param>
        /// <returns></returns>
       public bool CheckUserFavEvent(int memberid, int eventid)
        {
            return EventsDALFactory.Create(this.LanguageID).CheckUserFavEvent(memberid, eventid) > 0;
        }

        /// <summary>
        /// 用于查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
         public DataSet  GDataSet (string sql)
         {
             return EventsDALFactory.Create(this.LanguageID).GDataSet(sql);
         }

        /// <summary>
        /// 取最近活动的举办日期
        /// </summary>
        /// <returns></returns>
        public IList<EventBeginDate> GBeginDates()
        {
            return EventsDALFactory.Create(this.LanguageID).GBeginDates();
        }

    }
}
